package com.daixin.blog.service;

import com.daixin.blog.mapper.UserMapper;
import com.daixin.blog.model.User;
import com.daixin.blog.model.UserExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Author daixin
 */
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    public void createOrUpdate(User user) {
        UserExample userExample = new UserExample();
        userExample.createCriteria()
                .andAccountIdEqualTo(user.getAccountId());
        List<User> users = userMapper.selectByExample(userExample);
        if (users.size() == 0) {
            user.setGmtCreat(System.currentTimeMillis());//设置创建时间
            user.setGmtModified(user.getGmtModified());
            userMapper.insert(user);
        }else {
            User dbUser = users.get(0);
            User updateUser = new User();
            updateUser.setGmtModified(System.currentTimeMillis());//把修改时间设置为当前时间
            updateUser.setName(user.getName());//名字
            updateUser.setToken(user.getToken());
            updateUser.setAvatarUrl(user.getAvatarUrl());//头像
            updateUser.setBio(user.getBio());//简介
            UserExample example = new UserExample();
            example.createCriteria()
                    .andIdEqualTo(dbUser.getId());
            userMapper.updateByExampleSelective(updateUser, example);
        }
    }
}
